
package com.kugou.game.sdk.ui.activity;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.kugou.framework.base.BaseWorkerFragmentActivity;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.entity.UnionPayRequestParams;
import com.kugou.game.sdk.protocol.YiPayTask;
import com.kugou.game.sdk.protocol.YiPayTask.YiPayHttpResponse;
import com.payeco.android.plugin.PayecoPluginLoadingActivity;

/**
 * 描述:易联支付中转类
 *
 * @author wcj
 * @since 2015年12月3日 上午10:27:23
 */
public class UPPayBridgeActivity extends BaseWorkerFragmentActivity {

    private final int MSG_BACK_UNIONPAY_REQUEST = 1;

    private final int MSG_REQUEST_DATA_SUCCESS = 2;

    private UnionPayRequestParams requestParams;

    /**
     * @Fields payecoPayBroadcastReceiver : 易联支付插件广播
     */
    private BroadcastReceiver payecoPayBroadcastReceiver;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestParams = (UnionPayRequestParams) getIntent().getSerializableExtra("request_params");
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        // window异常，所以延迟发送
        sendEmptyBackgroundMessageDelayed(MSG_BACK_UNIONPAY_REQUEST, 200);

        // 初始化支付结果广播接收器
        initPayecoPayBroadcastReceiver();

        // 注册支付结果广播接收器
        registerPayecoPayBroadcastReceiver();
    }

    // 初始化支付结果广播接收器
    private void initPayecoPayBroadcastReceiver() {
        payecoPayBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // 接收易联支付插件的广播回调
                String action = intent.getAction();
                if (!SDKActions.ACTION_YI_PAY_SUCCESS.equals(action)) {
                    Log.e("test", "接收到广播，但与注册的名称不一致[" + action + "]");
                    return;
                }

                // 商户的业务处理
                String result = intent.getExtras().getString("upPay.Rsp");
                Log.i("test", "接收到广播内容：" + result);

                /*
                 * 支付成功1，支付失败2，支付取消3
                 */

                try {
                    JSONObject json = new JSONObject(result);
                    if (json.has("respCode")) {

                        String respCode = json.getString("respCode");
                        if ("W101".equals(respCode)) { // W101订单未支付，用户主动退出插件
                            setResultAndFinish(3, "支付操作已取消");
                            return;
                        }

                        if (!"0000".equals(respCode)) { // 非0000，订单支付响应异常
                            String respDesc = json.getString("respDesc");
                            setResultAndFinish(2, respDesc);
                            return;
                        }
                    }

                    if (json.has("Status")) {
                        String status = "";
                        if ("01".equals(json.getString("Status"))) {
                            status = "未支付";
                        } else if ("02".equals(json.getString("Status"))) {
                            status = "已支付";
                            setResultAndFinish(1, status);
                            return;
                        } else if ("03".equals(json.getString("Status"))) {
                            status = "已退款(全额撤销/冲正)";
                        } else if ("04".equals(json.getString("Status"))) {
                            status = "已过期";
                        } else if ("05".equals(json.getString("Status"))) {
                            status = "已作废";
                        } else if ("06".equals(json.getString("Status"))) {
                            status = "支付中";
                        } else if ("07".equals(json.getString("Status"))) {
                            status = "退款中";
                        } else if ("08".equals(json.getString("Status"))) {
                            status = "已被商户撤销";
                        } else if ("09".equals(json.getString("Status"))) {
                            status = "已被持卡人撤销";
                        } else if ("10".equals(json.getString("Status"))) {
                            status = "调账-支付成功";
                        } else if ("11".equals(json.getString("Status"))) {
                            status = "调账-退款成功";
                        } else if ("12".equals(json.getString("Status"))) {
                            status = "已退货";
                        }

                        setResultAndFinish(2, status);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        };
    }

    /**
     * @Title registerPayecoPayBroadcastReceiver
     * @Description 注册广播接收器
     */
    private void registerPayecoPayBroadcastReceiver() {

        IntentFilter filter = new IntentFilter();
        filter.addAction(SDKActions.ACTION_YI_PAY_SUCCESS);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        registerReceiver(payecoPayBroadcastReceiver, filter);
    }

    /**
     * @Title unRegisterPayecoPayBroadcastReceiver
     * @Description 注销广播接收器
     */
    private void unRegisterPayecoPayBroadcastReceiver() {

        if (payecoPayBroadcastReceiver != null) {
            unregisterReceiver(payecoPayBroadcastReceiver);
            payecoPayBroadcastReceiver = null;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);
        if (this.isFinishing()) {
            return;
        }
        switch (msg.what) {
            case MSG_REQUEST_DATA_SUCCESS:
                if (msg.obj != null && ((YiPayHttpResponse) msg.obj).isOk()) {
                    YiPayHttpResponse rr = (YiPayHttpResponse) msg.obj;
                    if (rr.isUseful()) {

                        // 全额抵扣
                        if (rr.getResultCode() == 2) {
                            setResultAndFinish(1, "已支付");
                            return;
                        }

                        String tn = rr.getResultTn();
                        if (TextUtils.isEmpty(tn)) {
                            setResultAndFinish(2, rr.getPrompt());
                            return;
                        }

                        // 跳转至易联支付插件
                        Intent intent = new Intent(this, PayecoPluginLoadingActivity.class);
                        intent.putExtra("upPay.Req", tn);
                        intent.putExtra("Broadcast", SDKActions.ACTION_YI_PAY_SUCCESS); // 广播接收地址
                        intent.putExtra("Environment", "01"); // 00:测试环境,01:生产环境
                        startActivity(intent);

                    } else {
                        setResultAndFinish(2, rr.getPrompt());
                    }
                } else {
                    setResultAndFinish(2, "网络异常");
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);
        switch (msg.what) {
            case MSG_BACK_UNIONPAY_REQUEST:
                if (requestParams == null) {
                    return;
                }

                YiPayTask task = new YiPayTask();
                YiPayHttpResponse response = task.request(requestParams);
                Message message = new Message();
                message.what = MSG_REQUEST_DATA_SUCCESS;
                message.obj = response;
                sendUiMessage(message);
                break;
            default:
                break;
        }
    }

    /**
     * @param resultCode 1:支付成功；2：支付失败；3：用户取消支付
     * @param ResultDescription
     */
    private void setResultAndFinish(int resultCode, String ResultDescription) {
        Intent intent = new Intent();
        intent.putExtra("pay_result", resultCode);
        intent.putExtra("result_description", ResultDescription);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        unRegisterPayecoPayBroadcastReceiver();
        super.onDestroy();
    }
}
